package com.bcxj.serviceSsePush.controller;

import com.bcxj.internalcommon.util.SsePrefixUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: SSEController
 * Package: com.bcxj.serviceSsePush.controller
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/11/21 09:36
 * @Version 1.0
 * @Since 1.0
 */
@RestController
@RequestMapping
public class SSEController {

    // map存连接
    public static Map<String, SseEmitter> sseEmitterMap = new HashMap<>();

    /**
     * 连接的建立
     * @param driverId
     * @return
     */
    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam("driverId") String driverId, @RequestParam("identity") String identity) {
        String key = SsePrefixUtils.generatorSseKey(driverId, identity);
        System.out.println("用户的key为" + key);
        // 如果有资源直接返回即可
        if(sseEmitterMap.containsKey(key)) {
            return sseEmitterMap.get(key);
        }

        SseEmitter sseEmitter = new SseEmitter(0L); // 为0表示永远不会超时

        sseEmitterMap.put(key, sseEmitter);
        return sseEmitter;
    }


    /**
     * 消息推送
     * @param driverId
     * @param content
     * @return
     */
    @GetMapping("/connect/push")
    public String push(@RequestParam("driverId") String driverId, @RequestParam("identity") String identity, @RequestParam("content") String content) {

        String key = SsePrefixUtils.generatorSseKey(driverId, identity);
        if(!sseEmitterMap.containsKey(key)) {
            return "连接未建立，推送失败";
        }
        // 获取连接
        SseEmitter sseEmitter = sseEmitterMap.get(key);

        // 发送消息
        try {
            sseEmitter.send(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return "给用户" + key + ", 发送了消息：" + content;

    }


    /**
     * 资源关闭
     * @param driverId
     * @return
     */
    @GetMapping("/connect/close")
    public String close(@RequestParam("driverId") String driverId, @RequestParam("identity") String identity) {
        System.out.println("关闭" + driverId + "的资源");
        String key = SsePrefixUtils.generatorSseKey(driverId, identity);
        // 移除资源
        sseEmitterMap.remove(key);
        return "close 成功";
    }

}
